package com.youjiang.springboot.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.youjiang.springboot.dao.UserDao;
import com.youjiang.springboot.mapper.UserMapper;
import com.youjiang.springboot.mapper.UserMapperCustom;
import com.youjiang.springboot.po.User;
import com.youjiang.springboot.pojo.Page;
import com.youjiang.springboot.pojo.UserPOJO;
import com.youjiang.springboot.service.UserService;
import com.youjiang.springboot.utils.JsonFormatUtils;
import com.youjiang.springboot.utils.PageUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/**
 * Description: 用户操作服务层实现类
 * Company: youjiang
 * @author Kwum
 * @date 2017年4月21日 上午9:44:21
 * @version 1.0
 */
@Service
@Transactional
public class UserServiceImpl implements UserService{
	
	@Resource
	private UserDao userDao;
	@Resource
	private UserMapper userMapper;
	@Resource
	private UserMapperCustom userMapperCustom;

	@Override
	public JSONObject selectUserPageDataByState(int state, int currentPage, int totalCount) throws Exception {
		JSONObject result = new JSONObject();
		
		//分页查找数据库中的用户数据
		UserPOJO uSQL = new UserPOJO();
		uSQL.setState(state);
		Page page;
		//只有第一页有总页数信息
		if(currentPage>=2){
			page = PageUtils.createPage(totalCount, currentPage);
		}else{
			int count = userDao.countUserByState(state);
			page = PageUtils.createPage(totalCount, count, currentPage);
			if(count == 0){
				result.put("totalPage", count);
			}else{
				result.put("totalPage", page.getTotalPage());
			}
		}
		uSQL.setPage(page);
		List<User> list = userMapperCustom.selectUserPageDataByState(uSQL);
		
		//列表数据转成页面显示的json数据
		result.put("listData", montageUserListData(list));
		return JsonFormatUtils.formatReturn(result);
	}

	public JSONObject addUser(String nick) throws Exception {
		
		//插入用户数据
		userDao.insertUser(nick);
		
		return JsonFormatUtils.formatReturn(1);
	}

	@Override
	public JSONObject updateUser(int userId, int state, String nick) throws Exception {
		
		//更新用户数据
		userDao.updateUser(userId, state, nick);
		
		return JsonFormatUtils.formatReturn(1);
	}

	@Override
	public JSONArray montageUserListData(List<User> list) throws Exception {
		
		return JSONArray.fromObject(list);
	}

	@Override
	public JSONObject montageUserInfoData(User user) throws Exception {
		
		return JsonFormatUtils.formatReturn(JSONObject.fromObject(user));
	}

}
